package com.crecheng.shop.controller;

import com.alibaba.fastjson.JSON;
import com.crecheng.shop.DAO.ItemData;
import com.crecheng.shop.Manage.ItemManage;
import com.crecheng.shop.util.MyMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/item")
public class ItemController {

    @RequestMapping("/get")
    public @ResponseBody
    String get(@RequestParam(value = "id",defaultValue = "-1")int id,
               @RequestParam(value = "name",defaultValue = "")String name){
        if(id<1) {
            if(name.length()<1)
                return JSON.toJSONString(ItemManage.getAll());
            else
                return JSON.toJSONString(ItemManage.get(" name like '%"+name+"%' "));
        }
        else
            return JSON.toJSONString(ItemManage.get(id));
    }

    @RequestMapping("/add")
    public @ResponseBody
    String add(@RequestParam(value = "name",defaultValue = "")String name,
               @RequestParam(value = "description",defaultValue = "")String description,
               @RequestParam(value = "remark",defaultValue = "")String remark){
        name=name.trim();
        description=description.trim();
        remark=remark.trim();
        if(name.length()<1||description.length()<1||remark.length()<1)
            return MyMessage.defaultError;

        ItemData data=new ItemData();
        data.set(name,description,remark);
        if(ItemManage.add(data))
            return MyMessage.defaultSuccess;
        else
            return MyMessage.defaultSqlError;
    }
}
